// pages/vip/buy_vip.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
    uid: '',
    user_name: '请点击登录',
    user_info: {},
    chosen_index: 0,
    if_read: false,
    amount: 3.8,
    combo_list: [{
      title:'1个月',
      price: 3.8
    },{
      title:'3个月',
      price: 7.8
    },],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init_data()
  },
  init_data() {
    this.setData({
      uid: util.getAppValue(App.globalData.uid),
      user_info: App.globalData.userInfo,
    })
    if (this.data.user_info.avatarUrl) {
      this.setData({
        avatar_url:this.data.user_info.avatarUrl,
        user_name: this.data.user_info.nickName
      })
    }
  },
  selecting(e) {
    this.setData({
      if_read: !this.data.if_read
    })
  },
  select_combo(e) {
    this.setData({
      chosen_index: e.currentTarget.dataset.index,
      amount: e.currentTarget.dataset.price
    })
  },
  buying_vip() {
    if (!this.data.if_read) {
      util.showToast('请先阅读协议')
      return
    }
    this.paying()
  },
  paying() {
    // 基本的请求参数信息
    let post_data = {
      uid: this.data.uid,
      type: 1,
      total_fee: this.data.amount
    }
    // 开始支付流程
    request.post(api.orderadd, post_data).then(res=>{
      let post_data = {
        id: res
      }
      
      request.post(api.orderpay, post_data).then(res=>{
        this.wx_pay(res)
      })
    })
  },  
  wx_pay(res) {
    let post_data = res
        wx.requestPayment({
          nonceStr: post_data.nonceStr,
          package: post_data.package,
          paySign: post_data.paySign,
          timeStamp: post_data.timeStamp,
          signType: post_data.signType,
          success(res) {
            util.showSuccess('开通成功');
            App.globalData.vip = true
            wx.reLaunch({
              url: '/pages/order/pay_success',
            })
          },
          fail(e) {
            util.showToast('开通取消');
          }
        })
    //   },
    //   fail: e=>{
    //   }
    // })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})